package com.supermap.search.activity;

import android.content.Context;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.supermap.greendao.XunJianOneTimeDao;
import com.supermap.search.R;
import com.supermap.search.Url_name;
import com.supermap.search.base.BaseActivity;
import com.supermap.search.javabean.XunJianOneTime;
import com.supermap.search.sys.loc.LocationApplication;
import com.supermap.search.utils.NetUtil;
import com.supermap.search.utils.SpUtils;
import com.supermap.search.utils.TimeUtils;
import com.yolanda.nohttp.Binary;
import com.yolanda.nohttp.FileBinary;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.RequestMethod;
import com.yolanda.nohttp.rest.RequestQueue;
import com.yolanda.nohttp.rest.Response;
import com.yolanda.nohttp.rest.SimpleResponseListener;
import com.yolanda.nohttp.rest.StringRequest;

import org.apache.commons.lang.StringUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by wyw on 2017/4/21.
 */

public class ShangBaoActivity extends BaseActivity {
    @BindView(R.id.spinner_wentileixing)
    Spinner spinnerWentileixing;
    @BindView(R.id.spinner_yanzhongchengdu)
    Spinner spinnerYanzhongchengdu;
    @BindView(R.id.shangbaodian)
    TextView shangbaodian;
    @BindView(R.id.bt_dingwei)
    Button btDingwei;
    @BindView(R.id.iv_kaiqicamer)
    Button ivKaiqicamer;
    @BindView(R.id.iv_localphoto)
    Button ivLocalphoto;
    @BindView(R.id.ll_camer)
    LinearLayout llCamer;
    @BindView(R.id.bt_xinzeng)
    Button btXinzeng;
    @BindView(R.id.et_wentiqingkuang)
    EditText etWentiqingkuang;
    @BindView(R.id.ll_pb_shangbao)
    LinearLayout llPbShangbao;
    private Context context;
    private static final String FILE_PATH = "/sdcard/shenzhen/";
    private static String PHOTO_PATH = "/sdcard/shenzhen/";
    private StringBuffer sb_camer;

    private RequestQueue requestQueue;
    private StringRequest stringRequest;
    private SharedPreferences sp;
    private XunJianOneTimeDao dao;
    private double x;
    private double y;
    private String result;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_shangbao;
    }

    @Override
    protected void init() {
        requestQueue = NoHttp.newRequestQueue();
        sb_camer = new StringBuffer();
        sp = getSharedPreferences(Url_name.SP, 0);
        dao = LocationApplication.getInstance().getDaoSession().getXunJianOneTimeDao();

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        setToolBarTitle("上报问题");
        context = ShangBaoActivity.this;
        PHOTO_PATH = "";
    }

    @OnClick({R.id.bt_dingwei, R.id.iv_kaiqicamer, R.id.iv_localphoto, R.id.bt_xinzeng})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bt_dingwei:
                dingwei();
                break;
            case R.id.iv_kaiqicamer:
                takePhoto();
                break;
            case R.id.iv_localphoto:
                localPhoto();
                break;
            case R.id.bt_xinzeng:
                shangbao();
                break;
        }
    }

    private void dingwei() {
        Intent intent = new Intent(context, MainActivity.class);
        intent.putExtra("shangbao", 11);
        startActivityForResult(intent, 2);
    }

    private void takePhoto() {
        Random random = new Random();
        int a = random.nextInt(1000000000);
        Intent intent = new Intent();
        // 指定开启系统相机的Action
        intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.addCategory(Intent.CATEGORY_DEFAULT);
//                             根据文件地址创建文件
        File file = new File(FILE_PATH + a + ".jpg");
        PHOTO_PATH = FILE_PATH + a + ".jpg";
//                           file_path.add(PHOTO_PATH);
        // 把文件地址转换成Uri格式
        Uri uri = Uri.fromFile(file);
        // 设置系统相机拍摄照片完成后图片文件的存放地址
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        startActivityForResult(intent, 0);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.i("aaaaa", "系统相机拍照完成，resultCode=" + resultCode);
        if (resultCode==0){

        }else {
            if (requestCode == 0) {
                ImageView imageView = new ImageView(context);
                llCamer.addView(imageView, 350, 400);
                Glide.with(context)
                        .load(PHOTO_PATH)
                        .into(imageView);
                sb_camer.append(PHOTO_PATH + "##");
            } else if (requestCode == 1) {
                ImageView imageView = new ImageView(context);
                llCamer.addView(imageView, 350, 400);
                Uri picUri = data.getData();
                Glide.with(context)
                        .load(picUri)
                        .into(imageView);
                sb_camer.append(getPath(picUri) + "##");
            } else if (requestCode == 2) {
                x = data.getDoubleExtra("X", 0);
                y = data.getDoubleExtra("Y", 0);
                shangbaodian.setText("已定位问题位置信息");
            } else if (resultCode==RESULT_OK&&requestCode==111){
                Bundle bundle=data.getExtras();
                if (bundle!=null) {
                    String result = bundle.getString("result");
                    Toast.makeText(ShangBaoActivity.this, result, Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    private String getPath(Uri contentUri) {
        String[] proj = {MediaStore.Images.Media.DATA};
        String result = null;
        if (contentUri==null||contentUri.equals("")||contentUri.equals("null")){
            
        }else {
            CursorLoader loader = new CursorLoader(getApplicationContext(), contentUri, proj, null, null, null);
            Cursor cursor = loader.loadInBackground();
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
             result =  cursor.getString(column_index);
            cursor.close();
        }
        return result;
    }

    private void localPhoto() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        // Start the Intent
        startActivityForResult(intent, 1);
    }

    private void shangbao() {
        //这是严重程度的代码

        String yanzhongchengdu = spinnerYanzhongchengdu.getSelectedItem().toString();

        //这是问题类型的代码

        String wentileixing = spinnerWentileixing.getSelectedItem().toString();
        String wentiqingkuang = etWentiqingkuang.getText().toString().trim();

        if (shangbaodian.getText().toString().equals("无定位信息")){
            Toast.makeText(this, "请定位问题位置", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(wentiqingkuang)) {
            Toast.makeText(this, "问题情况不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
//        File file = new File(PHOTO_PATH);
        if (!TextUtils.isEmpty(sb_camer.toString())) {
            String all_photo = sb_camer.toString();
            upNetShangBao(yanzhongchengdu, wentiqingkuang, all_photo, wentileixing);
        } else {
            Toast.makeText(this, "照片不能为空", Toast.LENGTH_SHORT).show();
        }
    }

    private void upNetShangBao(final String yanzhongchengdu, final String wentiqingkuang, final String photopath, final String wentileixing) {
        llPbShangbao.setVisibility(View.VISIBLE);
//        先判定有沒有网络
        if (NetUtil.isNetworkConnected(context)) {
//             有网络，上传
            stringRequest = new StringRequest(Url_name.POST_XUNJIAN, RequestMethod.POST);
            stringRequest.add("cENTERX", x);
            stringRequest.add("cENTERY", y);
            stringRequest.add("EQTYPENAME",wentileixing);
            stringRequest.add("PROBLEMDESC", wentiqingkuang);
            stringRequest.add("SEVERITYLEVEL", yanzhongchengdu);
            stringRequest.add("REPORTUSERID", sp.getString("pkid", ""));
            List<String> photo = SpUtils.stringToList(photopath);
            List<Binary> fileList = new ArrayList<>();
            fileList.clear();
            for (int i = 0; i < photo.size(); i++) {
                fileList.add(new FileBinary(new File(photo.get(i))));
            }
            if (fileList.size() > 0) {
//                当有图片的时候
                stringRequest.add("image", fileList);
            }
            requestQueue.add(1, stringRequest, new SimpleResponseListener<String>() {
                @Override
                public void onSucceed(int what, Response<String> response) {
                    llPbShangbao.setVisibility(View.GONE);
                    Toast.makeText(context, "上传成功！", Toast.LENGTH_SHORT).show();
                    finish();
                }

                @Override
                public void onFailed(int what, String url, Object tag, Exception exception, int responseCode, long networkMillis) {
                    saveLocal(yanzhongchengdu, wentiqingkuang, photopath, wentileixing,x,y);
                    Toast.makeText(context, "上传失败，已保存本地", Toast.LENGTH_SHORT).show();
                }
            });
        } else {
            saveLocal(yanzhongchengdu, wentiqingkuang, photopath, wentileixing,x,y);
            Toast.makeText(context, "无网络，已保存本地", Toast.LENGTH_SHORT).show();
        }
    }

    private void saveLocal(String yanzhongchengdu, String wentiqingkuang, String photopath, String wentileixing, double x, double y ) {
        XunJianOneTime xunJianOneTime = new XunJianOneTime();
        xunJianOneTime.setWentiqingkuang(nullToStr(wentiqingkuang));
        xunJianOneTime.setYanzhongchengdu(nullToStr(yanzhongchengdu));
        xunJianOneTime.setPhotopath(nullToStr(photopath));
        xunJianOneTime.setX(x+"");
        xunJianOneTime.setY(y+"");
        xunJianOneTime.setWentileixing(nullToStr(wentileixing));
        xunJianOneTime.setState("1");
        xunJianOneTime.setReportTime(TimeUtils.getNowTimeString());
        XunJianOneTimeDao.createTable(LocationApplication.getInstance().getDaoSession().getDatabase(),true);
        dao.insert(xunJianOneTime);
        llPbShangbao.setVisibility(View.GONE);
        finish();
    }

    private String nullToStr(String str){
        if(StringUtils.isEmpty(str)){
            return "";
        }
        return str;
    }



}
